package com.easyidea.its.domain.repository.operationrecord.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.easyidea.its.domain.model.system.OperationRecord;
import com.easyidea.its.domain.repository.base.impl.BaseRepositoryImpl;
import com.easyidea.its.domain.repository.operationrecord.OperationRecordRepository;
import com.easyidea.its.util.DateUtil;

public class OperationRecordRepositoryImpl extends
		BaseRepositoryImpl<OperationRecord> implements
		OperationRecordRepository {

	public List<OperationRecord> getOperationRecords(Date startDate,
			Date endDate, int startAtIndex, int pageSize) {
		Criteria ca = this.getOperationRecordsCriteria(startDate, endDate);
		if(startAtIndex > 0) {
			ca.setFirstResult(startAtIndex);
		}
		if (pageSize > 0) {
			ca.setMaxResults(pageSize);
		}		
		return ca.list();
	}

	public int getOperationRecordsCount(Date startDate, Date endDate) {
		// TODO Auto-generated method stub
		Criteria ca = this.getOperationRecordsCriteria(startDate, endDate);
		ca.setProjection(Projections.count("id"));
		return (Integer)ca.uniqueResult();		
	}

	private Criteria  getOperationRecordsCriteria(Date startDate, Date endDate) {
		Criteria ca = this.createUndeleteCriteria();
		if (startDate != null && endDate != null) {
			ca.add(Restrictions.between("operationDate", DateUtil.getStartTime(startDate), DateUtil.getEndTime(endDate)));	
		}
		ca.addOrder(Order.desc("operationDate"));
		return ca;  
		
	}
}
